#ifndef YHAIDA_COUNTDOWNLATCH_H
#define YHAIDA_COUNTDOWNLATCH_H
#include "../mutex/MutexLock.h"
#include "../mutex/Condition.h"

#include "../base/Utils.h"
namespace yhaida
{
    class CountDownLatch : Utils::nocapyable
    {
    public:
        CountDownLatch(int count) : _mutex(), _cv(_mutex), _value(count){};
        ~CountDownLatch() = default;

        int get()
        {
            MutexLockGuard guard(_mutex);
            return _value;
        }

        void wait()
        {
            MutexLockGuard guard(_mutex);
            while (_value > 0)
            {
                _cv.wait();
            }
        }
        void downLatch()
        {
            MutexLockGuard guard(_mutex);
            --_value;
            if (_value == 0)
            {
                _cv.notifyAll();
            }
        }

    private:
        MutexLock _mutex;
        Condition _cv;
        int _value;
    };
}

#endif